package me.algo.g;

import java.util.Objects;

/**
 * @author guozheng
 * @date 2024/4/24
 */
public class G1 {
    public static void main(String[] args) {
        char[][] board = new char[][]{
                {'X', 'X', 'X', 'X' },
                {'X', 'O', 'O', 'X' },
                {'X', 'X', 'O', 'X' },
                {'X', 'O', 'X', 'X' }
        };
//        solve(board);
//        System.out.println(board);
        char[][] ccc = new char[][]{
                {'O', 'X', 'X', 'O', 'X'},
                {'X', 'O', 'O', 'X', 'O'},
                {'X', 'O', 'X', 'O', 'X'},
                {'O', 'X', 'O', 'O', 'O'},
                {'X', 'X', 'O', 'X', 'O'}
        };

        solve(ccc);
        System.out.println(ccc);
    }

    /**
     * 130. 被围绕的区域
     * @param board
     */
    public static void solve(char[][] board) {
        if (Objects.isNull(board) || board.length == 0 || board[0].length == 0) {
            return;
        }
        int right = board.length - 1;
        char ooo = 'O';

        for (int line = 0; line < board.length; line++) {
            int bottom = board[line].length-1;
            for (int j = 0; j <= bottom; j++) {
                if (line == 0 || j == 0 || line == right || j == bottom) {
                    if (board[line][j] == ooo) {
                        board[line][j] = '1';
                    }
                }
            }
        }
        boolean hasNext = false;
        do {
            int ct = 0;
            for (int line = 1; line < board.length - 1; line++) {
                int bottom = board[line].length;
                for (int j = 1; j < bottom - 1; j++) {
                    char tp = board[line - 1][j];
                    char lp = board[line][j - 1];
                    char bp = board[line + 1][j];
                    char rp = board[line][j + 1];
                    char c = board[line][j];
                    if ((tp == '1' || lp == '1' || bp == '1' || rp == '1') && c == ooo) {
                        board[line][j] = '1';
                        ct++;
                    }
                }
            }
            if (ct > 0) {
                hasNext = true;
            } else {
                hasNext = false;
            }
        } while (hasNext);
        for (int line = 0; line < board.length; line++) {
            int bottom = board[line].length;
            for (int j = 0; j < bottom; j++) {
                if (board[line][j] == ooo) {
                    board[line][j] = 'X';
                }
            }
        }
        for (int line = 0; line < board.length; line++) {
            int bottom = board[line].length;
            for (int j = 0; j < bottom; j++) {
                if (board[line][j] == '1') {
                    board[line][j] = ooo;
                }
            }
        }
    }
}
